package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.hh.timeselector.timeutil.datedialog.DateListener;
import com.hh.timeselector.timeutil.datedialog.TimeConfig;
import com.hh.timeselector.timeutil.datedialog.TimeSelectorDialog;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.utils.InstanceUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeRiChangActivity extends BaseActivity implements View.OnClickListener {
    private EditText cid_rc_change;//编号
    private EditText dwid_rc_change;//单位(编号)
    private EditText checkTime_rc_change;//巡查时间
    private ImageView checkTime_rc_img_change;//获取当前时间
    private EditText remarks_rc_change;//备注
    private TextView save_change_rc;
    private TextView cancle_change_rc;
    private static final List<RegisterRolePirVO> stypes = new ArrayList<RegisterRolePirVO>();
    private static final List<RegisterRolePirVO> steps = new ArrayList<RegisterRolePirVO>();
    private Map<String, EditText> textMap = new HashMap<String, EditText>();
    private Map<String, Map<String, Object>> resultMap;
    private CustomApplication application;
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(ChangeRiChangActivity.this, RiChangeActivity.class);

                    startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_ri_chang);
        init();
        //根据ID查询后台数据
        Intent intent = getIntent();
        System.out.println(intent.getStringExtra("recid"));
        getWangGeInfo(intent.getStringExtra("recid"));
    }



    protected void init(){
        application = (CustomApplication) getApplication();
        cid_rc_change = (EditText)findViewById(R.id.cid_rc_change);
        textMap.put("cid", cid_rc_change);
        dwid_rc_change = (EditText)findViewById(R.id.dwid_rc_change);
        textMap.put("dwid", dwid_rc_change);
        checkTime_rc_change = (EditText)findViewById(R.id.checkTime_rc_change);
        textMap.put("checktime", checkTime_rc_change);
        checkTime_rc_img_change = (ImageView)findViewById(R.id.checkTime_rc_img_change);
        remarks_rc_change = (EditText)findViewById(R.id.remarks_rc_change);
        textMap.put("remarks", remarks_rc_change);
        save_change_rc = (TextView)findViewById(R.id.save_change_rc);
        cancle_change_rc = (TextView)findViewById(R.id.cancle_change_rc);
        checkTime_rc_img_change.setOnClickListener(this);
        save_change_rc.setOnClickListener(this);
        cancle_change_rc.setOnClickListener(this);
    }
    //todo 2017/5/16 进读
    private void getWangGeInfo(final String cid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                Request request=null;
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    request = new Request.Builder().url(ConfUtils.SERVICE_URL + "inspect/update/c_aj_rcxc-" + cid).post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        resultMap = gson.fromJson(result, Map.class);
                        //System.out.println(resultMap);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (final Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (textMap.get(entry.getKey()) != null) {
                                        textMap.get(entry.getKey()).setText(entry.getValue().toString().contains(".") ? entry.getValue().toString().split("\\.")[0] : entry.getValue().toString());
                                        textMap.get(entry.getKey()).setEnabled ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));
                                        textMap.get(entry.getKey()).setFocusable ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));
                                    }
                                }
                            }
                        });

                    }else {
                        Message message = new Message();
                        message.what = 0;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                } finally {
                    if(response!=null)response.close();

                }
            }
        }).start();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.checkTime_rc_img_change:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String date = sdf.format(new Date());
                showDatePickDialog(TimeConfig.YEAR_MONTH_DAY_HOUR_MINUTE,date);
                break;
            case R.id.save_change_rc:
                String dwid_rc_change_str = dwid_rc_change.getText().toString();
                String checkTime_rc_change_str = checkTime_rc_change.getText().toString();
                String remarks_rc_change_str = remarks_rc_change.getText().toString();
                if ("".equals(dwid_rc_change_str)
                        || "".equals(checkTime_rc_change_str)
                        || "".equals(remarks_rc_change_str)
                        ) {
                    Toast.makeText(getApplicationContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Response response = null;
                            try {
                                OkHttpClient client = new OkHttpClient();
                                //String _id = new DBHelper(changVo).queryBycn(entry.getValue().getText().toString());
                                FormBody.Builder builder = new FormBody.Builder()
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                for (Map.Entry<String, EditText> entry : textMap.entrySet()) {

                                    resultMap.get("result").put(entry.getKey(), entry.getValue().getText().toString());

                                }

                                for (Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (entry.getValue() instanceof String) {
                                        builder.add(entry.getKey(), (String) entry.getValue());
                                    }
                                }
                                RequestBody requestBody = builder.build();
                                Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doUpdate/c_aj_rcxc").post(requestBody).build();
                                response = client.newCall(request).execute();
                                if (response.isSuccessful()) {//成功
                                    String result = response.body().string();
                                    System.out.println("result:" + result);
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    if ((boolean) resultMap.get("success")) {
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                    }
                                } else {
                                    Message message = new Message();
                                    message.what = 0;
                                    handler.sendMessage(message);
                                }
                            } catch (Exception e) {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            } finally {
                                if (response != null) response.close();

                            }
                        }
                    }).start();

                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            case R.id.cancle_change_rc:
//                Intent intent = new Intent(ChangeRiChangActivity.this, RiChangeActivity.class);
//                startActivity(intent);
                finish();
                break;
        }
    }

    private void showDatePickDialog(int type,String date) {
        TimeSelectorDialog dialog = new TimeSelectorDialog(this);
        //设置标题
        dialog.setTimeTitle("选择时间:");
        //显示类型
        dialog.setIsShowtype(TimeConfig.YEAR_MONTH_DAY_HOUR_MINUTE);
        //默认时间
        dialog.setCurrentDate(date);
        //隐藏清除按钮
        dialog.setEmptyIsShow(false);
        dialog.setDateListener(new DateListener() {
            @Override
            public void onReturnDate(String time,int year, int month, int day, int hour, int minute, int isShowType) {
                checkTime_rc_change.setText(time);
            }
            @Override
            public void onReturnDate(String empty) {
                checkTime_rc_change.setText(empty);
            }
        });
        dialog.show();
    }
}
